XF.Visitor = new function() {
	/*this.backSpace = function(obj) {
		var name = $(obj).prev().attr("name");
		var v = $("input[name="+name+"]").val();
		if(v.length-1 >= 0){
			v=v.substring(0,v.length-1);
			$("input[name="+name+"]").val(v);
			$("input[name="+name+"]").focus();
		}	
				
	}
	this.backExp = function(obj) {
		var id = $(obj).prev().attr("id");
		var v = $("#"+id).val();
		if(v.length-1 >= 0){
			v=v.substring(0,v.length-1);
			$("#"+id).val(v);
			$("#"+id).focus();
		}	
				
	}*/
	
	/**
	 * 打开拍照窗口
	 */
	this.openPhoto = function() {
		var camera ='<div id="my_photo_booth">'
			camera+='<div id="Camera" style="margin:0 auto;margin-top: 30px;margin-bottom: 30px"></div>'
			camera+='<form class="webcam" style="margin-top: 15px; ">'
			camera+='<div id="pre_take_buttons">'
			camera+='<input style="margin-right: 15px;" class="a-btn-microsoft" type=button value="拍照" onClick="XF.Visitor.preview_snapshot()">'
			camera+='</div>'
			camera+='<div id="post_take_buttons" style="display:none">'
			camera+='<input class="a-btn-microsoft" style="margin-right: 15px;" type=button value="重拍" onClick="XF.Visitor.cancel_preview()">'
			camera+='<input class="a-btn-microsoft" style="margin-right: 15px;" type=button value="确定" onClick="XF.Visitor.save_photo()" style="font-weight:bold;">'
			camera+='</div>'			
			camera+='</form>'
			camera+='</div>'
			camera+='<div id="results" style="display:none"></div>'	;
		layer.open({
			  type: 1,
			  title:"拍摄照片",
			  skin: 'layui-layer-rim', //加上边框
			  area: ['660px', '540px'], //宽高
			  content: camera,
			  cancel: function(){
				  Webcam.reset();
			  }
			});
		XF.Visitor.photograph();
		
	}
	
	//打开摄像头
	this.photograph = function() {
		Webcam.set({
			// 实时预览大小
			width: 320,
			height: 240,			
			// 拍摄大小
			dest_width: 640,
			dest_height: 480,			
			// 最后裁剪大小
			crop_width: 640,
			crop_height: 480,
			image_format: 'png',
			jpeg_quality: 99
		});
		Webcam.attach( '#Camera' );
	}
	//拍照
	this.preview_snapshot = function() {
		Webcam.freeze();
		document.getElementById('pre_take_buttons').style.display = 'none';
		document.getElementById('post_take_buttons').style.display = '';
	}
	//查看相片
	this.openImg = function(photoname) {		
		var img = null;
		if(photoname == null){
			var imgBase64 = $("#photo").val();
			img = '<img src="data:image/png;base64,'+imgBase64+'"/>';
		}else{
			img = '<img src="'+global.contextPath+'/imagextra/'+photoname+'"/>';
		}
		layer.open({
			  type: 1,
			  title:"查看相片",
			  skin: 'layui-layer-rim', //加上边框
			  area: ['660px', '540px'], //宽高
			  content: img,
			});
	}
	//重拍
	 this.cancel_preview = function() {
		Webcam.unfreeze();
		document.getElementById('pre_take_buttons').style.display = '';
		document.getElementById('post_take_buttons').style.display = 'none';
	}
	
	//确认相片
	this.save_photo = function() {		
			Webcam.snap( function(data_uri) {
				document.getElementById('results').innerHTML ='<img src="'+data_uri+'"/>'
				$('#openImg').attr("href","javascript:XF.Visitor.openImg()").css("display","inline");
				$('#photo').val(data_uri.substr(22));
				//$('#photo').val(data_uri);
				Webcam.reset();
				document.getElementById('results').style.display = '';
				document.getElementById('my_photo_booth').style.display = 'none';
			} );		
	}

	
	//登记自动补全
	this.bigAutocomp = function(sid) {
		var staffid = sid;
		var url = global.contextPath + "/visitor/getReg?staffid="+staffid
		$("input[name='vname']").autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: url,
                    dataType: "json",
                    data:{
                        vname: request.term
                    },
                    success: function( data ) {
                        response( $.map( data.datas, function( item ) {
                            return {
                        		label:item.label,
                                value:item.vname,
                                vid:item.vid,
                                vaudit:item.vaudit,
                                cert:item.cert,
                                units:item.units,
                                certtype:item.certtype,
                                phone:item.phone,
                                depa:item.depa,
                                byvisitor:item.byvisitor
                            }
                        }));
                    }
                });
            },
            minLength: 1,
            select: function( event, ui ) {
            	if(ui.item.vid != null){
    				$("input[name='vid']").val(ui.item.vid);
    				$("input[name='vaudit']").val(ui.item.vaudit);
    			}									 
    			$("input[name='cert']").val(ui.item.cert);
    			$("input[name='units']").val(ui.item.units);
    			$("#certtype").val(ui.item.certtype);						  
    			$("input[name='phone']").val(ui.item.phone);
    			$("#depa").val(ui.item.depa);
    			$("input[name='byvisitor']").val(ui.item.byvisitor);	
            }
        });		
	}
	
	/**
	 * 生成二维码
	 */
	this.newQrcode = function(vname,vid) {
		var title = "打印"+vname+"二维码";
		$('#userdetail_popwin').window({
			title: title
		});
		$('#userdetail_popwin').window('open');
		$('#userdetail_popwin').empty();
		var url  = window.location.href+"/visitor/doQrcode?vid="+vid
		$('#userdetail_popwin').append("<div class='qrcode' id='qrcode' style='padding-top:10px;' align='center'>")
		$('#qrcode').qrcode({
			render: "canvas",
			text: url,
			width: "150",               //二维码的宽度  
			height: "150",              //二维码的高度
			background: "#ffffff",       //二维码的后景色  
			foreground: "#000000",        //二维码的前景色 
			imgWidth:"75",
			imgHeight:"25",   				//二维码的前景色
			src: window.location.href+'/images/xf_logo_no_bg.png'             //二维码中间的图片
		});
		var canvas = $('.qrcode canvas')
		var img = canvas[0].toDataURL("image/png")
		$('.qrcode').html("<img src='" + img + "'>")
		$('#userdetail_popwin').next().remove()
        $("#userdetail_popwin").after("<div class='printBtnWrap' style='padding-top:20px;'><a  href='javascript:XF.Visitor.print()' class='a-btn-microsoft'>打印</a></div>");
			
	}
	//打印条形码加访客信息
	this.printInfo = function(vid,vname,certtype,cert,units,phone,peoplenum,byvisitor,depa,aim,visittime,remark) {		
		var visitorInfo = '<div class="visitorInfo"><div style = "text-align: left;text-indent: 6em;margin-top: 12px;">访客信息</div>';
			visitorInfo+= '<div style="text-align: left;margin-left: 20px;"><img id="barcode"  ></img></div>';
			visitorInfo+= '<div class="v_Info" style="text-align:left;text-indent:2em;line-height:150%;font-size:12px;">';
			visitorInfo+= '<p>访客姓名：'+vname+'</p>';
			visitorInfo+= '<p>证件类型：'+certtype+'</p>';
			visitorInfo+= '<p>证件号码：'+cert+'</p>';
			visitorInfo+= '<p>访客单位：'+units+'</p>';
			visitorInfo+= '<p>联系电话：'+phone+'</p>';
			visitorInfo+= '<p>人数：'+peoplenum+' 人</p>';
			visitorInfo+= '<p>被访人：'+byvisitor+'</p>';
			visitorInfo+= '<p>被访部门：'+depa+'</p>';
			visitorInfo+= '<p>事由：'+aim+'</p>';
			visitorInfo+= '<p>访问时间：'+visittime+'</p>';
			visitorInfo+= '<p>备注:'+remark+'</p>';
			visitorInfo+= '</div></div>';
			visitorInfo+= '<div style="padding-top:10px;"><a  href="javascript:XF.Visitor.print()" class="a-btn-microsoft">打印</a></div>';
		layer.open({
			  type: 1,
			  title:"访客信息",
			  skin: 'layui-layer-rim', //加上边框
			  area: ['200px', '450px'], //宽高
			  content: visitorInfo			 
			});	
		JsBarcode('#barcode',vid,{
			format: "CODE128",//选择要使用的条形码类型
			displayValue:true,//是否在条形码下方显示文字
			height:25,//条形高度
			text:vid,//覆盖显示的文本
			fontSize:14			
		})		
	}


	//打印脚本
	this.print = function (){
		//打印二维码
		/*var canvas = $('.qrcode canvas')
		var img = canvas[0].toDataURL("image/png")
		$('.qrcode').html("<img src='" + img + "'>")*/
		//打印条形码
		$('.visitorInfo').printArea()
	}
	
	/**
	 * 访客登记
	 */
	this.addVisitor = function(){
		XF.lightSideBar("addVisitor");
		var url  = global.contextPath + "/visitor/addVisitor"
		$.ajax({
		  url: url,
		  type: "post",
		  data: {},
		  complete: function(xhr){
			  xhr = xhr['responseText'];
			  $("#visitorCenter").html(xhr);
		  }
		});
	};
	
	/**
	 * 编辑访客
	 */
	this.editVisitor = function(vid){
		var url  = global.contextPath + "/visitor/editVisitor"
		$.ajax({
		  url: url,
		  type: "post",
		  data: {vid:vid},
		  complete: function(xhr){
			  xhr = xhr['responseText'];
			  if (xhr.indexOf("SomeRandomString") != -1) {
				  $("#visitorCenter").html(xhr);
			  } else {
				  $.messager.show({
						title:'提示',
						msg:'超过五分钟不能修改！',
						timeout:5000,
						showType:'slide'
				  });
			  } 
		  }		  
		});
	};
	
	/**
	 * 添加编辑失败错误提示
	 */
	this.refreshAfterAddFaild = function(errorJson){
		if(typeof(errorJson)=="undefined")return;
		if(errorJson==null || errorJson=="")return;
		$("span[id*='errorTip']").hide();
		for(key in errorJson){
			var v = errorJson[key];
			var errorTip = $("#errorTip_"+key);
			errorTip.html(v);
			errorTip.show();
		}
	};
	
	/**
	 * 访客管理
	 */
	this.listVisitor = function(){
		XF.lightSideBar("visitorList");
		_visitor_search('VISITTIME','DESC',null,null,null,null,null);
	}
	/**
	 * 通用调用方法
	 */
	
	this.listVisitorSearch = function(){
		var orderByField = 'VISITTIME';
		var orderByMode = 'DESC';
		var username = null;
		var visittimeStart = null;
		var visittimeEnd = null;
		var vname = null;
		var vid = null;
		vname = $("input[name=vname]").val();
		vid = $("input[name=vid]").val();
		username = $("input[name=username]").val();
		visittimeStart = $("#visittimeStart").val();
		if(!XF.Visitor.checkDate(visittimeStart)){
			return false;
		};
		visittimeEnd = $("#visittimeEnd").val();
		if(!XF.Visitor.checkDate(visittimeEnd)){
			return false;
		};
		if(typeof(orderByFieldReq)!='undefined' && orderByFieldReq!=""){
			orderByField = orderByFieldReq;
			var td = $("th[orderByField="+orderByField+"]");
			orderByMode = td.find("span.px").attr("orderByMode");
		}
		_visitor_search(orderByField,orderByMode,username, vname, vid,visittimeStart,visittimeEnd);
	};
	
	this.refreshAfterVisitorFaild = function(errorJson){
		if(typeof(errorJson)=="undefined")return;
		if(errorJson==null || errorJson=="")return;
		$("span[id*='errorTip']").hide();
		for(key in errorJson){
			var v = errorJson[key];
			var errorTip = $("#errorTip_"+key);
			errorTip.html(v);
			errorTip.show();
		} 
	};
	
	/**
     * 具体搜索方法实现
     */
    function _visitor_search(orderByField,orderByMode,username, vname, vid,visittimeStart,visittimeEnd){
    	config.visitor_search['args'] = [orderByField,orderByMode,username, vname, vid,visittimeStart,visittimeEnd];
    	SMT.xconfig.gvar.pageNum = '1';
    	SMT.ajax(config.visitor_search);
    }
    	
		
	this.doOut = function(vid){
		var url  = global.contextPath + "/visitor/doOut"
		$.ajax({
		  url: url,
		  type: "post",
		  data: {vid:vid},
		  complete: function(xhr){
			  xhr = xhr['responseText'];
			  xhr = new Function("return " + xhr);
			  xhr = xhr();
			  var status = xhr['status'];
			  if("SUCCESS"==status){
				  var msg = xhr['msg'];
				  $.messager.show({
					title:'提示',
					msg:msg,
					timeout:5000,
					showType:'slide'
				  });
				  XF.Visitor.listVisitor();
			  }
		  }
		});
	}
	
	
	
	
	/*快递登记管理*/
	
	/**
	 * 快递登记
	 */
	this.addExpress = function(){
		XF.lightSideBar("addExpress");
		var url  = global.contextPath + "/visitor/addExpress"
		$.ajax({
		  url: url,
		  type: "post",
		  data: {},
		  complete: function(xhr){
			  xhr = xhr['responseText'];
			  $("#visitorCenter").html(xhr);
		  }
		});
	};
	
	/**
	 * 编辑快递
	 */
	this.editExpress = function(exid){
		var url  = global.contextPath + "/visitor/editExpress"
		$.ajax({
		  url: url,
		  type: "post",
		  data: {exid:exid},
		  complete: function(xhr){
			  xhr = xhr['responseText'];
			  if (xhr.indexOf("SomeRandomString") != -1) {
				  $("#visitorCenter").html(xhr);
			  } else {
				  $.messager.show({
						title:'提示',
						msg:'超过五分钟不能修改！',
						timeout:5000,
						showType:'slide'
				  });
			  } 
		  }		  
		});
	};
	
	
	
	/**
	 * 快递列表
	 */
	this.listExpress = function(){
		XF.lightSideBar("expressList");
		_express_search('ADDTIME','DESC',null,null,null,null);
	}
	/**
	 * 通用调用方法
	 */
	this.listExpressSearch = function(){
		var orderByField = 'ADDTIME';
		var orderByMode = 'DESC';
		var username = null;
		var exnum = null;
		var addtimeStart = null;
		var addtimeEnd = null;
		username = $("input[name=username]").val();
		exnum = $("input[name=exnum]").val();
		addtimeStart = $("#addtimeStart").val();
		if(!XF.Visitor.checkDate(addtimeStart)){
			return false;
		};
		addtimeEnd = $("#addtimeEnd").val();
		if(!XF.Visitor.checkDate(addtimeEnd)){
			return false;
		};
		if(typeof(orderByFieldReq)!='undefined' && orderByFieldReq!=""){
			orderByField = orderByFieldReq;
			var td = $("th[orderByField="+orderByField+"]");
			orderByMode = td.find("span.px").attr("orderByMode");
		}
		_express_search(orderByField,orderByMode,username,exnum,addtimeStart,addtimeEnd);
	};
	
	this.refreshAfterExpressFaild = function(errorJson){
		if(typeof(errorJson)=="undefined")return;
		if(errorJson==null || errorJson=="")return;
		$("span[id*='errorTip']").hide();
		for(key in errorJson){
			var v = errorJson[key];
			var errorTip = $("#errorTip_"+key);
			errorTip.html(v);
			errorTip.show();
		} 
	};
	
	/**
     * 具体搜索方法实现
     */
    function _express_search(orderByField,orderByMode,username,exnum,addtimeStart,addtimeEnd){
    	config.express_search['args'] = [orderByField,orderByMode,username,exnum,addtimeStart,addtimeEnd];
    	SMT.xconfig.gvar.pageNum = '1';
    	SMT.ajax(config.express_search);
    }
    
    this.deleteExpress = function(exid,userid){
		$.messager.confirm('提示',"确认删除这条记录？",function(r){
		    if (r){
				var url  = global.contextPath + "/visitor/doDeleteExpress"
				$.ajax({
				  url: url,
				  type: "post",
				  data: {exid:exid,userid:userid},
				  complete: function(xhr){
					  xhr = xhr['responseText'];
					  xhr = new Function("return " + xhr);
					  xhr = xhr();
					  xhr = xhr['status'];
					  if(xhr=="SUCCESS"){
						  $.messager.show({
							title:'提示',
							msg:'删除成功',
							timeout:3000,
							showType:'slide'
						  });
						  $(".userListWrap tr i[s="+exid+"]").parent().parent().parent().remove();
					  }else if(xhr=="FAILD"){
						  $.messager.show({
							title:'提示',
							msg:'删除失败,超过五分钟不能删除！',
							timeout:5000,
							showType:'slide'
						  });
					  }
				   }
				});
		    }
		});
	};
	
	
	/**************预约方法*******************************/
	/**
	 * 预约登记
	 */
	this.addAppoint = function(){		
		XF.lightSideBar("addAppoint");
		var url  = global.contextPath + "/visitor/addAppoint"
		$.ajax({
		  url: url,
		  type: "post",
		  data: {},
		  complete: function(xhr){
			  xhr = xhr['responseText'];
			  $("#visitorCenter").html(xhr);
		  }
		});
	};
	
	/**
	 * 编辑预约
	 */
	this.editAppoint = function(vid){
		var url  = global.contextPath + "/visitor/editAppoint"
		$.ajax({
		  url: url,
		  type: "post",
		  data: {vid:vid},
		  complete: function(xhr){
			  xhr = xhr['responseText'];
			  if (xhr.indexOf("SomeRandomString") != -1) {
				  $("#visitorCenter").html(xhr);
			  } else {
				  $.messager.show({
						title:'提示',
						msg:'已经访问公司的访客不能修改或服务器出错！',
						timeout:5000,
						showType:'slide'
				  });
			  } 
		  }		  
		});
	};
		
	
	/**
	 * 我的预约管理
	 */
	this.listMyAppoint = function(staffid){
		XF.lightSideBar("myAppointList");
		var sid = staffid + "";
		_appoint_search('APPOINTTIME','DESC',sid,null,null,null,null,null,null);
	}
	/**
	 * 保安预约管理
	 */
	this.listAppoint = function(status,vaudit){
		XF.lightSideBar("appointList");
		var st = status + "";
		var va = vaudit+""
		_appoint_search('APPOINTTIME','DESC',null,null,st,va,null,null);
	}
	/**
	 * 通用调用方法
	 */
	this.checkDate = function(DateStr) {
		if(DateStr != ""){
			var dArr = DateStr.replace(/(^\s+|\s+$)/g,'').split('-');
			var year = parseInt(dArr[0]);
			var mon = parseInt(dArr[1]);
			var day = parseInt(dArr[2]);
			if(year > 0 && mon > 0 && day > 0){
				if(year < 2017 || year > 2050){
					alert("日期超过有效年份最小2017最大2050");
					return false;
				}
				if(mon < 1 || mon>12){
					alert("日期月份格式错误");
					return false;
				}
				if( (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)){
					if(mon == 2 && day > 29){
					alert("日期日份格式错误：闰年"+mon+"月只有29天")
					return false;
					}
				}else{
					if(mon == 2 && day > 28){
						alert("日期日份格式错误："+mon+"月只有28天")
						return false;
					}
				}
				if(mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12){
					if(day > 31){
						alert("日期日份格式错误："+mon+"月只有31天")
						return false;
					}
				}else if(mon == 4 || mon == 6 || mon == 9 || mon == 11){
					if(day > 30){
						alert("日期日份格式错误："+mon+"月只有30天")
						return false;
					}
				}
				return true;
			}else{
				alert("日期格式错误最小2017年最大2050年,例2017-1-1。");
				return false;
			}			
		}else{
			return true;
		}
	}
	this.listAppointSearch = function(){
		var orderByField = 'APPOINTTIME';
		var orderByMode = 'DESC';
		var staffid = null;
		var appointtimeStart = null;
		var appointtimeEnd = null;
		var vname = null;
		var status = null;
		var vaudit = null;
		vname = $("input[name=vname]").val();
		staffid = $("#staffid").val();
		status = $("#status").val();
		vaudit = $("input[name=vaudit]").val();
		appointtimeStart = $("#appointtimeStart").val();
		if(!XF.Visitor.checkDate(appointtimeStart)){
			return false;
		};
		appointtimeEnd = $("#appointtimeEnd").val();
		if(!XF.Visitor.checkDate(appointtimeEnd)){
			return false;
		};
		if(typeof(orderByFieldReq)!='undefined' && orderByFieldReq!=""){
			orderByField = orderByFieldReq;
			var td = $("th[orderByField="+orderByField+"]");
			orderByMode = td.find("span.px").attr("orderByMode");
		}
		_appoint_search(orderByField,orderByMode,staffid, vname, status, vaudit, appointtimeStart, appointtimeEnd);
	};
	
	this.refreshAfterAppointFaild = function(errorJson){
		if(typeof(errorJson)=="undefined")return;
		if(errorJson==null || errorJson=="")return;
		$("span[id*='errorTip']").hide();
		for(key in errorJson){
			var v = errorJson[key];
			var errorTip = $("#errorTip_"+key);
			errorTip.html(v);
			errorTip.show();
		} 
	};
	
	/**
     * 具体搜索方法实现
     */
	 function _appoint_search(orderByField,orderByMode,staffid, vname, status,vaudit, appointtimeStart, appointtimeEnd){
	    	config.appoint_search['args'] = [orderByField,orderByMode,staffid, vname, status,vaudit, appointtimeStart, appointtimeEnd];
	    	SMT.xconfig.gvar.pageNum = '1';
	    	SMT.ajax(config.appoint_search);
	    }
    
    this.deleteAppoint = function(vid){
		$.messager.confirm('提示',"确认删除这条记录？",function(r){
		    if (r){
				var url  = global.contextPath + "/visitor/doDeleteAppoint"
				$.ajax({
				  url: url,
				  type: "post",
				  data: {vid:vid},
				  complete: function(xhr){
					  xhr = xhr['responseText'];
					  xhr = new Function("return " + xhr);
					  xhr = xhr();
					  xhr = xhr['status'];
					  if(xhr=="SUCCESS"){
						  $.messager.show({
							title:'提示',
							msg:'删除成功',
							timeout:3000,
							showType:'slide'
						  });
						  $(".userListWrap tr i[s="+vid+"]").parent().parent().parent().remove();
					  }else if(xhr=="FAILD"){
						  $.messager.show({
							title:'提示',
							msg:'删除失败,已经访问公司的访客不能删除',
							timeout:5000,
							showType:'slide'
						  });
					  }
				   }
				});
		    }
		});
	};
	
	/**
	 * 审核-执行
	 */
	this.doVaudit = function(vid){
		$("#auditTab"+vid).html("已确定");
		var url  = global.contextPath + "/visitor/doVaudit"
		$.ajax({
		  url: url,
		  type: "post",
		  data: {vid:vid},
		  complete: function(xhr){
			  xhr = xhr['responseText'];
			  xhr = new Function("return " + xhr);
			  xhr = xhr();
			  var status = xhr['status'];
			  if("SUCCESS"==status){
				  var msg = xhr['msg'];
				  $.messager.show({
					title:'提示',
					msg:msg,
					timeout:5000,
					showType:'slide'
				  });
			  }else{
				  var msg = xhr['msg'];
				  $.messager.show({
					title:'提示',
					msg:msg,
					timeout:5000,
					showType:'slide'
				  });
			  }
		  }
		});
	}
	
	
	
}
config.visitor_search = {
		url: ""+global.contextPath+"/visitor/listVisitor",
	    argsOrder: ['orderByField','orderByMode','username', 'vname', 'vid','visittimeStart','visittimeEnd'],
	    needVar: true,
	    replaceExp: '#visitorCenter',
	    callBack: function() {
	    }		
};

config.appoint_search = {
		url: ""+global.contextPath+"/visitor/listAppoint",
	    argsOrder: ['orderByField','orderByMode','staffid', 'vname', 'status', 'vaudit', 'appointtimeStart', 'appointtimeEnd'],
	    needVar: true,
	    replaceExp: '#visitorCenter',
	    callBack: function() {
	    }		
};


config.express_search = {
		url: ""+global.contextPath+"/visitor/listExpress",
	    argsOrder: ['orderByField','orderByMode','username','exnum','addtimeStart','addtimeEnd'],
	    needVar: true,
	    replaceExp: '#visitorCenter',
	    callBack: function() {
	    }		
};